package com.eastdigit.system.controller;

import com.eastdigit.servlet.DeptPermValidate;
import com.eastdigit.servlet.Response;
import com.eastdigit.system.model.Role;
import com.eastdigit.system.service.IRoleService;
import com.eastdigit.system.service.IUserRoleService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/userRole")
public class UserRoleController {

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject queryRoleByUser(@PathVariable("userId") String userId) {
        JSONArray array = new JSONArray();
        for (Role role : roleService.queryRoleOfUser(userId)) {
            JSONObject json = new JSONObject();
            json.put("roleId", role.getId());
            json.put("roleName", role.getName());
            json.put("deptId", role.getDeptId());
            array.add(json);
        }
        return Response.response(array);
    }

    @RequestMapping(value = "/{userId}/{roleId}", method = RequestMethod.PUT)
    @ResponseBody
    @DeptPermValidate(id = { "userId", "roleId" }, deptId = { "deptId", "deptId" })
    public JSONObject addUserRole(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId) {
        userRoleService.addUserRole(userId, roleId);
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/{userId}/{roleId}", method = RequestMethod.DELETE)
    @ResponseBody
    @DeptPermValidate(id = { "userId", "roleId" }, deptId = { "deptId", "deptId" })
    public JSONObject delUserRole(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId) {
        userRoleService.delUserRole(userId, roleId);
        return Response.responseSuccess();
    }

}
